<template>
  <view class="add-schedule">
    <NavBar
      v-if="appInfoStore().isH5"
      title="添加日程"
      :backgroundColor="'#fff'"
    />
    <view
      class="add-schedule-box"
      :class="{ 'padding-top-navbar': appInfoStore().isH5 }"
    >
      <nut-tabs
        v-model="activeTab"
        :swipeable="true"
        @change="changeTab"
      >
        <nut-tab-pane
          v-for="tab in tabs"
          :key="tab.id"
          :title="tab.title"
        >
          <view class="schedule">
            <view class="schedule-title-piece">
              <view class="add-schedule-title">
                <view class="schedule-title-text">添加标题</view>
                <textarea
                  placeholder="写下标题，让您的会议更出圈"
                  :auto-height="true"
                  placeholder-class="schedule-input-placeholder"
                  v-model="form.subject"
                />
              </view>
              <view class="schedule-title-user">
                <view class="schedule-participants">
                  <view
                    class="schedule-participants-top"
                    @click="addScheduleUser"
                  >
                    <view class="schedule-participants-text">
                      <i class="iconfont icon-duoren"></i>
                      <view class="schedule-participants-name">
                        <text>参与者</text>
                        <text>已添加{{ meetingPlayersImgs.length }}人</text>
                      </view>
                    </view>
                    <view class="schedule-participants-right">
                      <nut-col
                        v-for="itm in meetingPlayersImgs"
                        :key="itm.deptId"
                      >
                        <img
                          :src="itm.avatarUrls"
                          alt=""
                        />
                      </nut-col>
                      <view class="add-schedule-users">
                        <img
                          src="https://img.alicdn.com/imgextra/i3/1034622205/O1CN017hRVzG1S9wNaWoofX_!!1034622205.png"
                          alt=""
                        />
                      </view>
                    </view>
                  </view>
                  <view class="schedule-participants-bottom">
                    <view class="user-permission-left">
                      <view class="user-permission-left-name">参与者权限</view>
                    </view>
                    <view class="user-permission-right">
                      <picker
                        mode="selector"
                        :range="participantPermissionsList"
                        class="picker-date"
                        @change="handleParticChange"
                      >
                        <view class="position-picker">
                          <text
                            class="position-text"
                            v-if="participantPermissionsText"
                          >
                            {{ participantPermissionsText }}
                          </text>
                          <text
                            class="position-placeholder"
                            v-else
                          >
                            邀请参与者、修改日程
                          </text>
                          <i
                            class="iconfont icon-youjiantou1"
                            style="font-size: 12px; color: #c5c5c5; padding-left: 5px"
                          ></i>
                        </view>
                      </picker>
                    </view>
                  </view>
                </view>
              </view>
              <view
                class="schedule-title-adress"
                v-if="msType == 0"
              >
                <view class="schedule-title-adress-left">
                  <text><i class="iconfont icon-didian-copy"></i>地点</text>
                </view>
                <view class="schedule-title-adress-right">
                  <input
                    type="text"
                    v-model="form.position"
                    placeholder="请输入地点"
                    placeholder-style="color: #999"
                  />
                </view>
              </view>
              <view
                class="schedule-title-position"
                v-if="msType == 1"
              >
                <view class="schedule-title-position-left">
                  <text><i class="iconfont icon-didian-copy"></i>会议室</text>
                </view>
                <view class="schedule-title-position-right">
                  <picker
                    :range="roomList"
                    class="picker-date"
                    @change="handleAdressChange"
                  >
                    <view class="position-picker">
                      <text
                        class="position-text"
                        v-if="form.roomName"
                      >
                        {{ form.roomName }}
                      </text>
                      <text
                        class="position-placeholder"
                        v-else
                      >
                        请选择会议室
                      </text>
                      <i
                        class="iconfont icon-youjiantou1"
                        style="font-size: 12px; color: #c5c5c5; padding-left: 5px"
                      ></i>
                    </view>
                  </picker>
                </view>
              </view>
              <view class="schedule-title-time-box">
                <view class="schedule-title-date">
                  <text>
                    <i
                      class="iconfont icon-time"
                      style="font-size: 14px; color: #c5c5c5"
                    ></i>
                    日期
                  </text>
                  <picker
                    class="picker-date"
                    mode="date"
                    @change="bindDateChange"
                    :value="dateSelect"
                  >
                    <view class="picker date-text">
                      <text
                        v-if="dateSelect"
                        class="picker-text"
                        >{{ dateSelect }}
                      </text>
                      <text
                        v-else
                        class="picker-placeholder"
                        >请选择日期</text
                      >
                      <i
                        class="iconfont icon-rili"
                        style="font-size: 12px; color: #c5c5c5; padding-left: 10px"
                      ></i>
                    </view>
                  </picker>
                </view>
                <view class="schedule-title-time interval">
                  <text> 时间 </text>
                  <view class="picker-time-box">
                    <picker
                      class="picker-time"
                      mode="time"
                      @change="bindTimeChangeOne"
                      :value="time1"
                      :show="isPickerShow"
                    >
                      <view class="picker">
                        <text
                          v-if="time1"
                          class="picker-text"
                          >{{ time1 }}</text
                        >
                        <text
                          v-else
                          class="picker-placeholder"
                          >开始时间</text
                        >
                        <i
                          class="iconfont icon-time"
                          style="font-size: 12px; color: #c5c5c5; padding-left: 30px; box-sizing: border-box"
                        ></i>
                      </view>
                    </picker>
                    <text>-</text>
                    <picker
                      class="picker-time"
                      mode="time"
                      @change="bindTimeChangeTwo"
                      :start="time1"
                      :value="time2"
                    >
                      <view class="picker">
                        <text
                          v-if="time2"
                          class="picker-text"
                          >{{ time2 }}</text
                        >
                        <text
                          v-else
                          class="picker-placeholder"
                          >结束时间</text
                        >
                        <i
                          class="iconfont icon-time"
                          style="font-size: 12px; color: #c5c5c5; padding-left: 30px; box-sizing: border-box"
                        ></i>
                      </view>
                    </picker>
                  </view>
                </view>
              </view>
            </view>
            <view class="meeting-remind-other">
              <view class="meeting-remind-other-box">
                <view class="meeting-prompt">
                  <img
                    src="https://img.alicdn.com/imgextra/i1/1034622205/O1CN01pZtbPB1S9wNadb5Et_!!1034622205.png"
                    alt=""
                  />
                  <view class="prompt-text-box">
                    <view
                      class="meeting-prompt-text"
                      v-if="state.isShowPrompt"
                    >
                      <view class="prompt-text-top">
                        <img
                          src="https://img.alicdn.com/imgextra/i3/1034622205/O1CN01Cl2Cx11S9wNbjEyny_!!1034622205.png"
                          alt=""
                        />
                        <text> 备注会议事项！</text>
                      </view>
                      <view class="prompt-text-bottom"> 提前准备好会议需要，提升会议效率 </view>
                      <i
                        class="iconfont icon-cha"
                        style="font-size: 12px; position: absolute; right: 6px; top: 4px"
                        @click="closePrompt"
                      ></i>
                    </view>
                    <view class="prompt-remark">
                      <textarea
                        v-model="form.remark"
                        :auto-height="true"
                        placeholder="请输入备注信息"
                        placeholder-style="color: #999"
                      ></textarea>
                    </view>
                  </view>
                </view>
                <view class="remind-user">
                  <view class="remind-user-left">
                    <text><i class="iconfont icon-naozhong"></i>提醒参与者</text>
                  </view>
                  <view class="remind-user-right">
                    <picker
                      mode="selector"
                      :range="participantsTimeList"
                      class="picker-date"
                      @change="handleChange"
                    >
                      <view class="position-picker">
                        <text
                          class="position-text"
                          v-if="participantsTimeText"
                        >
                          {{ participantsTimeText }}
                        </text>
                        <text
                          class="position-placeholder"
                          v-else
                        >
                          请选择提醒时间
                        </text>
                        <i
                          class="iconfont icon-youjiantou1"
                          style="font-size: 12px; color: #c5c5c5; padding-left: 5px"
                        ></i>
                      </view>
                    </picker>
                  </view>
                </view>
                <view class="remind-uploader">
                  <view class="remind-uploader-box">
                    <i
                      class="iconfont icon-huixingzhen"
                      style="font-size: 10px; color: #c5c5c5"
                    ></i>
                    <uploads
                      @files="getFiles"
                      :path="form.path"
                    >
                      <text class="remind-form-upload">添加附件</text>
                    </uploads>
                  </view>
                </view>
              </view>
            </view>

            <view class="logo-bottom">
              <img
                src="https://img.alicdn.com/imgextra/i2/1034622205/O1CN01ROtCca1S9wNLeJ6zx_!!1034622205.png"
                alt=""
              />
            </view>
          </view>
        </nut-tab-pane>
      </nut-tabs>
    </view>
    <view
      class="add-schedule-btn"
      @click="submit"
    >
      <nut-button color="#1E74FD">{{ isEdit ? "修改" : "创建" }}{{ activeTab == 0 ? "日程" : "会议" }}</nut-button>
    </view>
    <addUserPopup
      :isUserPopup="isUserPopup"
      @update:visible="updateVisible"
      @selectedUsers="handleSelectedUsers"
      :feedbackUsers="meetingPlayersImgs"
    />
    <!-- <pickerOne
      :isShowPicker="state.isVisible"
      @execute="handleExecute"
      :roomNo="form.roomId"
      :initiate="form.initiate"
      :type="form.type"
    />
    <pickerTimeStart
      :isShowPicker="state.isVisibleTimeStart"
      @execute="handleExecuteTimeStart"
    /> -->
    <nut-dialog
      v-model:visible="visible1"
      @cancel="onCancel"
      @ok="onOk"
    >
      <view class="dialog-content">
        <view class="dialog-content-box">
          <view class="title"> 当前会议室非预约时间段 </view>
          <view
            class="dialog-content-item"
            v-for="(item, index) in alreadyTime"
            :key="index"
          >
            <text
              class="meetingState-text"
              :style="{ color: colorList[Number(item.meetingState)]?.color }"
              >{{ meetingStateList[Number(item.meetingState)]?.dictLabel }}</text
            >
            {{ item.time }}</view
          >
        </view>
      </view>
      <template v-slot:footer>
        <view class="dialog-footer">
          <nut-button
            type="default"
            @click="onCancel"
            >关闭</nut-button
          >
        </view>
      </template>
    </nut-dialog>
  </view>
</template>

<script setup lang="ts">
import NavBar from "@/components/navBar/index.vue";
import { appInfoStore } from "@/stores/appInfo";
import { onMounted, reactive, ref, toRefs, watch } from "vue";
import uploads from "@/components/uploads/index.vue";
import pickerOne from "@/components/pickerDate/index.vue";
import pickerTimeStart from "@/components/pickerTime/index.vue";
import { addMeeting, getSystemRoomList, getDictDataTypeList, queryMeeting, editMeeting } from "@/api/index";
import { getMeetingListReservation } from "@/api/index";
import Taro, { useRouter } from "@tarojs/taro";
import { IAddScheduleForm } from "./type";
const router = useRouter();
const value = reactive([0, 0, 0]);
const colorList = ref([
  { color: "#1E74FD", active: false },
  { color: "#F8B62D", active: false },
  { color: "#FF5E5E", active: false },
]);
const isUserPopup = ref(false); // 是否显示用户弹窗
const meetingPlayersImgs = ref([]);
const date = ref("");
const time1 = ref("");
const time2 = ref("");
const roomList = ref([]);
const msType = ref(0);
const visible1 = ref(false);
const dateSelect = ref(""); //日期选择
const isPickerShow = ref(false);
const state = reactive({
  textarea: "",
  // date: "",
  isVisible: false,
  isVisibleTimeStart: false,
  time: "",
  selectedYear: "",
  isShowPrompt: true,
});
const alreadyTime = ref([]);
const show = ref(false);
const isSchedule = ref(true); //是否是日程
const participantsTimeList = ref([]);
const participantsTimeText = ref("");
const participantPermissionsList = ref([]);
const participantPermissionsText = ref("");
const activeTab = ref(0);
const tabs = ref([
  { id: 0, title: "日程" },
  { id: 1, title: "会议" },
]);
const meetingStateList = ref([]);
const initFormData: IAddScheduleForm = {
  subject: "", // 会议主题
  meetingPlayers: undefined, //人员
  beginTime: "", // 会议时间
  endTime: "", // 会议时间
  position: "", // 地点
  roomId: "", // 会议室
  roomName: "", // 会议室NAME
  remark: "", // 备注
  participantsTime: null, // 提醒时间
  participantPermissions: null, // 参会权限
  type: 0, // 类型
  path: [], // 附件
};
// const roomNoText = ref("");
const data = reactive({
  form: { ...initFormData },
});

const dictList = ref([]);
const isEdit = ref(false);
const { form } = toRefs(data);
watch(activeTab, val => {
  let title = val == 0 ? "添加日程" : "添加会议";
  if (isEdit.value) {
    title = val == 0 ? "编辑日程" : "编辑会议";
  }
  Taro.setNavigationBarTitle({
    title: title,
  });
});
watch(isSchedule, val => {
  let myTitle = "添加日程"; //自定义标题
  if (router.params.isSMType == "1") {
    myTitle = "添加日程";
  } else {
    myTitle = "添加会议";
  }
  Taro.setNavigationBarTitle({
    title: myTitle,
  });
});
watch(isEdit, val => {
  let title = activeTab.value == 0 ? "编辑日程" : "编辑会议";
  Taro.setNavigationBarTitle({
    title: title,
  });
});
onMounted(async () => {
  isEdit.value = router.params.id != "" && router.params.id != undefined;
  isSchedule.value = router.params.isSMType == "1";
  activeTab.value = router.params.isSMType == "1" ? 0 : 1;
  getDictMeetingPurviewFun("meeting_status"); // 获取状态
  getDictMeetingPurviewFun("meeting_remind"); // 获取字典
  getDictMeetingPurviewFun("meeting_purview"); // 获取字典
  await handleMeetingRoomList();
  if (isEdit.value) {
    getQueryMeeting();
  }
});
const onCancel = () => {
  visible1.value = false;
};
const handleExecute = (val: any) => {
  state.isVisible = false;
  if (val) {
    date.value = val.birthday;
    form.value.beginTime = date.value + " " + time1.value + ":00";
    form.value.endTime = date.value + " " + time2.value + ":00";
    dateSelect.value =
      date.value.substring(0, 4) + "年" + date.value.substring(5, 7) + "月" + date.value.substring(8, 10) + "日";
  }
};
const handleExecuteTimeStart = (val: any) => {
  state.isVisibleTimeStart = false;
  if (val) {
    time1.value = val.birthday;
  }
};
const handleDateChange = (e: any) => {
  state.isVisible = true;
};
// 获取已用的日期
const handleMeetingListReservation = async date => {
  alreadyTime.value = [];
  await getMeetingListReservation({ roomNo: form.value.roomId, initiate: date }).then(res => {
    console.log(res.rows, "res.data");
    let resData = res.rows;
    resData.forEach((item: { beginTime: any; endTime: any }) => {
      let newdate = "";
      newdate = item.beginTime.substr(5, 11) + "-" + item.endTime.substr(5, 11);
      alreadyTime.value.push({
        time: newdate,
        meetingState: item.meetingState,
      });
    });
  });
  visible1.value = true;
  isPickerShow.value = true;
};
// 查询
const getQueryMeeting = () => {
  queryMeeting(router.params.id).then(res => {
    form.value = res.data;
    let meetingPlayers = res.data.meetingPlayers;
    meetingPlayers.map((item: { avatar: any; id: any }) => {
      meetingPlayersImgs.value.push({
        deptId: item.userId,
        avatarUrls: item.avatar,
      });
    });
    participantPermissionsText.value = participantPermissionsList.value[Number(form.value.participantPermissions)]; //参与者权限
    dateSelect.value = form.value.beginTime.split(" ")[0];
    // form.value.beginTime.split(" ")[0].substring(0, 4) +
    // "年" +
    // form.value.beginTime.split(" ")[0].substring(5, 7) +
    // "月" +
    // form.value.beginTime.split(" ")[0].substring(8, 10) +
    // "日";
    time1.value =
      form.value.beginTime.split(" ")[1].split(":")[0] + ":" + form.value.beginTime.split(" ")[1].split(":")[1];
    time2.value = form.value.endTime.split(" ")[1].split(":")[0] + ":" + form.value.endTime.split(" ")[1].split(":")[1];
    participantsTimeText.value = participantsTimeList.value[Number(form.value.participantsTime)]; // 提醒时间
    console.log(form.value.path, "path");
  });
};
// 字典获取（会议提醒）
const getDictMeetingPurviewFun = async dictType => {
  await getDictDataTypeList(dictType).then(res => {
    if (dictType == "meeting_remind") {
      let newList = res.data;
      newList.forEach((item: { dictLabel: any }) => {
        participantsTimeList.value.push(item.dictLabel);
      });
      participantsTimeList.value = JSON.parse(JSON.stringify(participantsTimeList.value));
    }
    if (dictType == "meeting_purview") {
      //参会权限
      let newList = res.data;
      newList.forEach((item: { dictLabel: any }) => {
        participantPermissionsList.value.push(item.dictLabel);
      });
      participantPermissionsList.value = JSON.parse(JSON.stringify(participantPermissionsList.value));
    }
    if (dictType == "meeting_status") {
      meetingStateList.value = res.data;
      console.log(meetingStateList.value, "item");
    }
  });
};
const getFiles = async (files: any) => {
  form.value.path = files;
};
//切换tab
const changeTab = (val: number) => {
  msType.value = activeTab.value;
  form.value.type = msType.value;
  date.value = "";
  dateSelect.value = "";
};
// 获取会议室列表
const handleMeetingRoomList = async () => {
  await getSystemRoomList().then(res => {
    let newList = res.rows;
    let newRoomList = [];
    newList.forEach((item: { name: any }, index: any) => {
      return newRoomList.push(item.name);
    });
    roomList.value = newRoomList;
    if (form.value.roomId == "" || form.value.roomId == undefined) {
      form.value.roomName = newList[0].name;
      form.value.roomId = newList[0].id;
    }
  });
};
// 修改
const editSchedule = () => {
  console.log("修改");
};

//
const addScheduleUser = () => {
  isUserPopup.value = true;
};
const updateVisible = (val: boolean) => {
  isUserPopup.value = val;
};
const handleSelectedUsers = (val: any) => {
  meetingPlayersImgs.value = val;
};
const handleParticChange = (e: { detail: { value: string | number } }) => {
  form.value.participantPermissions = e.detail.value;
  participantPermissionsText.value = participantPermissionsList.value[e.detail.value];
};
const handleChange = (e: { detail: { value: string | number } }) => {
  participantsTimeText.value = participantsTimeList.value[e.detail.value];
  form.value.participantsTime = e.detail.value; //提醒参与者
};
const handleAdressChange = async (e: { detail: { value: string | number } }) => {
  form.value.roomId = e.detail.value;
  form.value.roomName = roomList.value[e.detail.value];
};
const bindDateChange = (e: { detail: { value: string } }) => {
  date.value = e.detail.value;
  form.value.beginTime = date.value + " " + time1.value + ":00";
  form.value.endTime = date.value + " " + time2.value + ":00";
  dateSelect.value =
    date.value.substring(0, 4) + "年" + date.value.substring(5, 7) + "月" + date.value.substring(8, 10) + "日";
  if (form.value.type == 1) {
    handleMeetingListReservation(date.value);
  }
};
const bindTimeChangeOne = (e: { detail: { value: string } }) => {
  time1.value = e.detail.value;
  form.value.beginTime = date.value + " " + time1.value + ":00";
};
const bindTimeChangeTwo = (e: { detail: { value: string } }) => {
  time2.value = e.detail.value;
  form.value.endTime = date.value + " " + time2.value + ":00";
};
const handleStateTime = (e: { stopPropagation: () => void }) => {
  state.time = "";
  if (process.env.TARO_ENV === "weapp") {
    e.stopPropagation();
  }
};
// 提交
const submit = async () => {
  let parmas = {
    ...form.value,
    type: msType.value == 0 ? 1 : 2,
    meetingPlayers: meetingPlayersImgs.value.map(item => {
      return {
        userId: item.userId,
      };
    }),
    path: JSON.stringify(form.value.path),
  };

  if (form.value.subject == "") {
    return Taro.showToast({
      title: "请输入会议主题",
      icon: "none",
    });
  }
  if (form.value.id) {
    editMeeting(parmas).then(res => {
      Taro.showToast({
        title: "修改成功",
        icon: "none",
      });
      setTimeout(() => {
        Taro.navigateBack({
          delta: 1,
        });
      }, 1000);
    });
  } else {
    await addMeeting(parmas).then(res => {
      Taro.showToast({
        title: "添加成功",
        icon: "none",
      });
      setTimeout(() => {
        Taro.navigateBack({
          delta: 1,
        });
      }, 1000);
    });
  }
};
// 关闭提醒
const closePrompt = () => {
  state.isShowPrompt = false;
};
</script>

<style lang="less">
@import "./index.less";
// @import url("../../../../assets/css/index.css");
@import "@/assets/css/index.less";
</style>
